exports.__esModule = true;

var _axios = require('axios');

var _axios2 = _interopRequireDefault(_axios);

var _moment = require('moment');

var _moment2 = _interopRequireDefault(_moment);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

const isDev = think.env === 'development';

exports.default = class extends think.BaseSocket {
    constructor(ctx) {
        super(ctx);
        this.callConfig = {
            callServer: isDev ? 'http://39.129.35.72:4015' : 'http://172.16.11.23:8088',
            queuePauseDo: '/smartcrm_2018/index.php?m=api&a=queuePauseDo', // 设置分机状态
            clickCall: '/smartcrm_2018/index.php?m=api&a=clickCall', // 点击拨号，呼出电话
            pbxAMIFeedBackJson: '/smartcrm_2018/index.php?m=api&a=pbxAMIFeedBackJson',
            setHuzhuanInfo: '/smartcrm_2018/index.php?m=api&a=setHuzhuanInfo',
            callTransfer: '/smartcrm_2018/index.php?m=api&a=callTransfer',
            cdrData: '/smartcrm_2018/index.php?m=api&a=cdrData',
            editBlackPhone: '/smartcrm_2018/index.php?m=api&a=editBlackPhone',
            blackPhoneList: '/smartcrm_2018/index.php?m=api&a=blackPhoneList',
            loginName: 'ny',
            password: 'ny2018'
        };
    }

    /**
     * 查询通话流水
     */
    cdrDataAction() {
        var _this = this;

        return _asyncToGenerator(function* () {
            const {
                exten,
                startTime,
                endTime,
                phone_num,
                billsec
            } = _this.post('exten,startTime,endTime,phone_num,billsec');
            const data = {
                exten
            };
            if (startTime) data.startTime = startTime;
            if (endTime) data.endTime = endTime;
            if (phone_num) data.phone_num = phone_num;
            if (billsec) data.billsec = billsec;
            try {
                const Res = yield _axios2.default.post(_this.callConfig.callServer + _this.callConfig.cdrData, data);
                return _this.json(Res.data);
            } catch (error) {
                return _this.json({
                    error: 1
                });
            }
        })();
    }

    /**
     * 设置呼叫转移
     *
     * @returns
     */
    callTransferAction() {
        var _this2 = this;

        return _asyncToGenerator(function* () {
            const {
                type,
                exten,
                to_num
            } = _this2.post('type,exten,to_num');
            try {
                const Res = yield _axios2.default.post(_this2.callConfig.callServer + _this2.callConfig.callTransfer, {
                    type,
                    exten,
                    to_num
                });
                return _this2.json(Res.data);
            } catch (error) {
                return _this2.json({
                    error: 1
                });
            }
        })();
    }

    /**
     * 拨号
     *
     * @returns
     */
    clickCallAction() {
        var _this3 = this;

        return _asyncToGenerator(function* () {
            const {
                exten,
                phone
            } = _this3.post('exten,phone');
            const data = {
                exten,
                phone
            };
            try {
                const Res = yield _axios2.default.post(_this3.callConfig.callServer + _this3.callConfig.clickCall, {
                    exten,
                    phone
                });
                return _this3.json(Res.data);
            } catch (error) {
                return _this3.json({
                    error: 1
                });
            }
        })();
    }

    /**
     * 设置分机号状态
     *
     * @returns
     */
    queuePauseDoAction() {
        var _this4 = this;

        return _asyncToGenerator(function* () {
            const {
                exten,
                type,
                queue_id
            } = _this4.post('exten,type,queue_id');
            try {
                const Res = yield _axios2.default.post(_this4.callConfig.callServer + _this4.callConfig.queuePauseDo, {
                    exten,
                    type,
                    queue_id
                });
                return _this4.json(Res.data);
            } catch (error) {
                return _this4.json({
                    error: 1
                });
            }
        })();
    }

    /**
     * 来电弹屏
     */
    callScreenAction() {
        var _this5 = this;

        return _asyncToGenerator(function* () {
            const {
                phone_num,
                exten,
                uniqueid,
                call_province,
                call_city,
                call_corp
            } = _this5.post('phone_num,exten,uniqueid,call_province,call_city,call_corp'); // 来电号,分机号,通话流水唯一标识
            think.logger.warn('来电号码:' + phone_num, '分机号:' + exten, 'call_province:' + call_province, 'call_city:' + call_city, 'call_corp:' + call_corp);
            try {
                const callProvince = new Buffer(call_province, 'base64').toString();
                const callCity = new Buffer(call_city, 'base64').toString();
                const callCorp = new Buffer(call_corp, 'base64').toString();

                // const nameSpace = this.config("nameSpace");
                // const allUserExten = await think.Redis.hgetall(nameSpace.callExtenBind);
                const result = yield _this5.service('call/CallService').findUserByExten(exten);
                if (!think.isEmpty(result)) {
                    const userId = result.commissioner;

                    _this5.sendMsgByUserAction({
                        phone_num,
                        exten,
                        uniqueid,
                        call_province: callProvince,
                        call_city: callCity,
                        call_corp: callCorp
                    }, userId, 'call_screen');
                    const msgBody = { // socket消息体结构
                        title: '有客户来电', // 标题
                        type: 0, // 消息类型或标识
                        menuUrl: 'Platform', // (可选)路由菜单url，用于跳转菜单
                        result: { id: uniqueid }, // 消息体
                        sendDate: think.datetime(new Date()) // 发送时间
                    };
                    _this5.sendMsgByUserAction(msgBody, userId, 'msg_box');
                }
            } catch (e) {
                think.logger.error(e);
                return _this5.json({
                    code: 1,
                    msg: 'error'
                });
            }
            return _this5.json({
                code: 0,
                msg: 'success'
            });
        })();
    }

    /**
     * 分机实时状态变更
     */
    extenStateChangeAction() {
        var _this6 = this;

        return _asyncToGenerator(function* () {
            // const exten = this.post('exten');//分机号
            // const status = this.post('status'); //分机状态
            const {
                exten,
                status
            } = _this6.post('exten,status'); // 分机号,分机实时状态
            let msg = '';
            switch (Number(status)) {
                case 0:
                    msg = '空闲';
                    break;
                case 1:
                    msg = '通话中';
                    break;
                case 2:
                    msg = '忙';
                    break;
                case 4:
                    msg = '不可用';
                    break;
                case 8:
                    msg = '振铃中';
                    break;
                case 9:
                    msg = '振铃&通话中';
                    break;
                case 16:
                    msg = '呼叫保持';
                    break;
                case 17:
                    msg = '通话中&呼叫保持';
                    break;
            }
            const nameSpace = _this6.config('nameSpace');
            const allUserExten = yield think.Redis.hgetall(nameSpace.callExtenBind);
            const sendToUserIds = [];
            for (const userId in allUserExten) {
                if (Number(allUserExten[userId]) === Number(exten)) {
                    sendToUserIds.push(userId);
                }
            }
            try {
                if (sendToUserIds.length > 0) {
                    _this6.sendMsgByUserAction({
                        label: msg,
                        value: status
                    }, sendToUserIds, 'call_type');
                }
            } catch (e) {
                think.logger.error(e);
            }

            return _this6.json({
                code: 0,
                msg: 'success'
            });
        })();
    }

    /**
     * 查找我的分机号
     */
    findOneExtenAction() {
        var _this7 = this;

        return _asyncToGenerator(function* () {
            const userId = _this7.getUser().userId;
            const result = yield _this7.service('call/CallService').findExtenByUser(userId);
            if (!think.isEmpty(result)) {
                return _this7.successJson(result);
            }
            return _this7.errorJson('您还不是坐席人员,请联系管理员');
        })();
    }

    /**
     * 客户资料保存
     */
    saveCustomerAction() {
        var _this8 = this;

        return _asyncToGenerator(function* () {
            const {
                id,
                phone,
                real_name,
                customer_type,
                gender,
                address,
                age,
                remark,
                operator_id,
                last_call_date,
                source
            } = _this8.post('id,phone,real_name,customer_type,gender,address,age,remark,operator_id,last_call_date,source');
            try {
                const res = yield _this8.service('call/CallService').saveCustomer({
                    id,
                    phone,
                    real_name,
                    customer_type,
                    gender,
                    age,
                    remark,
                    address,
                    operator_id,
                    last_call_date,
                    source
                });
                return _this8.successJson(res, '保存成功');
            } catch (err) {
                think.logger.error(err);
                return _this8.errorJson('保存失败');
            }
        })();
    }

    /**
     * 工单提交
     */
    saveWorkOrderAction() {
        var _this9 = this;

        return _asyncToGenerator(function* () {
            const aj = think.ajaxJson();
            const data = _this9.post('create_by,create_date,objName,ObjPosition,BGID,parent_name,sub_name,area_code,group_code,remarks');
            data.baidu_x = Number(_this9.post('baidu_x'));
            data.baidu_y = Number(_this9.post('baidu_y'));
            data.source = Number(_this9.post('source'));
            data.type = Number(_this9.post('type'));
            data.update_date = data.create_date;
            data.update_by = data.create_by;
            if (data.area_code && data.group_code) {
                data.ObjCode = data.area_code + data.group_code;
            }
            const EventService = _this9.service('api/cms/EventService');
            const res = yield EventService.addEvent(data);

            if (res && res.error) {
                return _this9.errorJson('查询失败');
            }

            const userIds = yield _this9.getOnlineModuleByUser('jdsl');
            // const userAll= await this.getOnlineUserIds();
            const result = {
                title: '呼叫中心事件流转',
                date: (0, _moment2.default)(data.update_date).format('YYYY-MM-DD HH:mm:ss'),
                id: res.id,
                userIds: data.update_by
            };
            const msgbox = _this9.getSocketMsgBody(result);
            msgbox.menuUrl = 'accept';
            const obj = _this9.getSocketMsgBody(res);

            // 推给所有受理中心人员
            _this9.sendMsgByUserAction(obj, userIds, 'accept_screen');
            _this9.sendMsgByUserAction(msgbox, userIds, 'msg_box'); // 消息推送

            // this.sendMsgByUserAction(obj, userIds, 'control_center');

            return _this9.successJson();
        })();
    }

    /**
     * 设置黑名单
     */
    saveBlockPhoneAction() {
        var _this10 = this;

        return _asyncToGenerator(function* () {
            const aj = think.ajaxJson();
            const data = _this10.post('phone,user_name,type');

            try {
                const Res = yield _axios2.default.post(_this10.callConfig.callServer + _this10.callConfig.editBlackPhone, data);
                // let datacc = JSON.parse(JSON.stringify(Res.data));
                // console.log(datacc);
                return _this10.json(Res.data);
            } catch (err) {
                think.logger.error(err);
                return _this10.json({
                    error: 1,
                    msg: err
                });
            }
        })();
    }

    /**
     * 查询黑名单列表
     */
    getBlockPhoneAction() {
        var _this11 = this;

        return _asyncToGenerator(function* () {
            const aj = think.ajaxJson();
            const data = {
                phone: _this11.post('phone')
            };
            try {
                const Res = yield _axios2.default.post(_this11.callConfig.callServer + _this11.callConfig.blackPhoneList, data);
                return _this11.json(Res.data);
            } catch (err) {
                think.logger.error(err);
                return _this11.json({
                    error: 1,
                    msg: err
                });
            }
        })();
    }
};